<template>
	<main-content
		v-if="!showDetail"
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					label="账单周期:"
					class="flex-row-container"
					label-width="77px"
				>
					<el-date-picker
						v-model="searchTime"
						:picker-options="pickerOptionsMonth"
						format="yyyy-MM"
						type="monthrange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						:clearable="false"
					></el-date-picker>
				</el-form-item>
				<el-form-item
					label="数据统计:"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.proxyType"
						size="medium"
						:placeholder="$t('common.select_all')"
						@change="handleChangeType"
					>
						<el-option
							v-for="item in accountTypeArr"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="代理账号:"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model.trim="queryData.proxyName"
						:maxlength="11"
						clearable
						:disabled="queryData.proxyType == 0"
						autocomplete="off"
						v-symbols
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>
				<el-form-item class="flex-row-container">
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('90870152')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
				</el-form-item>
				<div
					v-if="queryData.proxyType !== 0"
					style="display: flex; width: 100%"
				>
					<el-checkbox
						v-model="checkAll"
						@change="handleCheckAllChange"
					>
						全选
					</el-checkbox>
					<span style="margin-left: 15px"></span>
					<el-checkbox-group
						v-model="checkedCities"
						@change="handleCheckedCitiesChange"
					>
						<el-checkbox
							v-for="(item, index) in cities"
							:label="item.value"
							:key="index"
						>
							{{ item.label }}
						</el-checkbox>
					</el-checkbox-group>
				</div>
			</el-form>
		</template>
		<template slot="content">
			<div class="totalContent">
				<div
					class="totalItem"
					v-for="[key, val] of Object.entries(totalSummaryTitle)"
					:key="key"
				>
					<div>
						<span>{{ val.label }}</span>
						<el-tooltip class="item" placement="top-start">
							<div slot="content" v-html="val.content"></div>
							<i class="el-icon-question"></i>
						</el-tooltip>
					</div>
					<div
						class="num"
						:style="handleNumberColor(totalSummary[key])"
					>
						{{
							handleNumber(
								'USTD',
								totalSummary[key],
								2,
								true,
								true
							)
						}}
					</div>
				</div>
			</div>
			<el-table
				v-loading="loading"
				ref="elTable"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:max-height="tableHeight"
				:data="tableData"
				:default-sort="{
					prop: 'staticsDate',
					order: 'descending'
				}"
				:key="headKey"
				v-bind="$attrs"
				v-on="$listeners"
				:cell-class-name="cellClassName"
				:header-cell-class-name="cellClassName"
				@sort-change="changeTableSort"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					v-for="(item, index) in newCol"
					:key="'column_' + index"
					:prop="newCol[index].prop"
					:align="item.alignCenter"
					:label="item.label"
					:min-width="item.minWidth"
					:fixed="item.isFixed"
					:sortable="item.isSortColumn"
					:show-overflow-tooltip="item.isShowTip"
				>
					<!-- 通过插槽为表头绑定mousedown和dragover方法 -->
					<template slot="header" slot-scope="{ column, $index }">
						<span
							@mousedown="
								handleMounseDown($event, column, $index)
							"
							@dragover="handleDragover($event, column, $index)"
							v-if="item.itemTipContent"
						>
							{{ item.label }}
						</span>
						<span
							@mousedown="
								handleMounseDown($event, column, $index)
							"
							@dragover="handleDragover($event, column, $index)"
							v-else
						>
							{{ item.label }}
						</span>
					</template>
					<template slot-scope="{ row }">
						<div v-if="item.solt === 'numberSolt'">
							<span
								:style="
									handleNumberColor(row[newCol[index].prop])
								"
							>
								{{
									handleNumber(
										'USDT',
										row[newCol[index].prop],
										2,
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'defaultSoltTime'">
							{{
								dayjs(String(row.cycleStartDate)).format(
									'YYYY-MM-DD'
								)
							}}
							00:00:00 至
							{{
								dayjs(String(row.cycleEndDate)).format(
									'YYYY-MM-DD'
								)
							}}
							23:59:59 ({{ row.cycleRemark }})
						</div>
						<div v-if="item.solt === 'proxyLevelSolt'">
							{{ row.proxyLevel }} / {{ row.proxyLevelName }}
						</div>
						<div v-if="item.solt === 'amountAbsSolt'">
							<span
								:style="
									handleNumberColor(row[newCol[index].prop])
								"
							>
								{{
									handleNumber(
										'USDT',
										row[newCol[index].prop],
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'aloneAddLast'">
							<span
								:style="
									handleNumberColor(
										shouldReceiptPaymentParentAmount
									)
								"
							>
								{{
									handleNumber(
										'USDT',
										row.shouldReceiptPaymentParentAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'aloneReduceLast'">
							<span
								:style="
									handleNumberColor(
										row.shouldReceiptPaymentParentAmount
									)
								"
							>
								{{
									handleNumber(
										'USDT',
										row.shouldReceiptPaymentParentAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'aloneAdd'">
							<span
								:style="
									handleNumberColor(
										row.personShouldReceiptPaymentAmount
									)
								"
							>
								{{
									handleNumber(
										'USDT',
										row.personShouldReceiptPaymentAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'aloneReduce'">
							<span
								:style="handleNumberColor(row.personNetAmount)"
							>
								{{
									handleNumber(
										'USDT',
										row.personNetAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<span
							v-if="
								item.solt === 'operate' &&
								hasPermission('90870153')
							"
						>
							<el-link
								class="lightBlueColor"
								type="primary"
								@click="goDetail(row)"
							>
								查看详情
							</el-link>
						</span>
						<div v-if="item.solt === 'defaultSolt'">
							<span>
								{{ row[newCol[index].prop] || '-' }}
							</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
	</main-content>
	<!-- 详情 -->
	<team-profit
		v-else
		:curData="rowData"
		@goBack="detailGoBackFn"
	></team-profit>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
// import Sortable from 'sortablejs'
import { Storage } from '@/utils/compose'
import summaryList from './components/summaryList'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'
import TeamProfit from './components/teamProfit'
const end = () => {
  return dayjs().endOf('month')
}
const start = () => {
  return dayjs()
    .subtract(3, 'month')
    .startOf('month')
}
const setSearchTime = () => [
  start(),
  end()
]
export default {
  name: routerNames.memberReturnData,
  components: {
    MainContent,
    TeamProfit
  },
  mixins: [list, summaryList],
  data() {
    return {
      dayjs,
      tableHeight: 480,
      otherDependenComponents: ['cardTableDetails'],
      accountTypeArr: [
        {
          value: 0,
          label: '全部总代'
        },
        {
          value: 1,
          label: '指定代理'
        }
      ],
      //   '仅看自身', '直属下级', '全部下级'
      cities: [
        {
          label: '仅看自身',
          value: 3
        },
        {
          label: '直属下级',
          value: 2
        },
        {
          label: '全部下级',
          value: 5
        }
      ],
      checkAll: false,
      checkedCities: [3],
      searchTime: setSearchTime(),
      curData: '',
      queryData: {
        proxyType: 0,
        labType: [],
        periodType: 5,
        billEndDate: ''
      },
      tableData: [],
      totalSummary: {
        teamSummary: '',
        teamZhanchengSummary: '',
        platSummary: ''
      },
      totalSummaryTitle: {
        teamSummary: {
          label: '代理团队净盈亏(总计)',

          content:
            `代理团队净盈亏(总计) =当前时间筛选范围内，所有「总代」团队的「净盈亏」金额之和。
            <br />
			注意，因为总代团队账单包含下级团队账单，这里只固定统计总代团队数据，用于运营看某段时间的平台整体盈亏。
			<br />
			单个总代的净盈亏=该总代账期内所有场馆的「净盈亏」之和。
			<br />
			单个场馆净盈亏=-(会员游戏输赢+输赢重算调整+有效投注返点+返点重算调整)。`
        },
        teamZhanchengSummary: {
          label: '代理团队占成盈亏(总计)',

          content:
            `代理团队占成盈亏(总计) =当前时间筛选范围内，所有总代团队的占成金额之和。
			 <br />
			 注意，因为总代团队账单包含下级团队账单，这里只固定统计总代团队数据，用于运营看某段时间的平台整体盈亏。
			 <br />
			单个总代的占成金额=该总代账期内所有场馆的占成金额之和，即该总代的团队盈亏金额。`
        },
        platSummary: {
          label: '平台占成盈亏(总计)',

          content:
            `平台占成盈亏(总计) =代理团队净盈亏(总计)  -  代理团队占成盈亏(总计)。
			<br />
			注意，因为总代团队账单包含下级团队账单，这里只固定统计总代团队数据，用于运营看某段时间的平台整体盈亏。
			  `
        }
      },
      detailData: {},
      loading: false,
      exportBtnLoading: false,
      oldCol: [],
      dropCol: [],
      newCol: [],
      childrenAjaxData: '',
      // 拖拽状态
      dragState: {
        start: -3, // 起始元素的 index 防止初始化cellStyle时序号、展开等默认样式改变，最好小于-3
        end: -3, // 移动鼠标时所覆盖的元素 index
        dragging: false, // 是否正在拖动
        direction: undefined // 拖动方向
      },
      headKey: 'agentRebateData', // 表头数组变换位置时，重绘table（不更新该值，表头数组变化时，页面不会改变）
      scrollX: 0, // 初始x轴scroll位置（用于定位X轴滚动条）
      showDetail: false // 是否显示占成账单详情
    }
  },
  computed: {},
  watch: {
    oldCol: {
      handler(newVal) {
        if (newVal) {
          setTimeout(() => {
            this.newCol = newVal.filter((its) => {
              return its.isShow === true
            })
          }, 1000)
        }
      },
      deep: true
    }
  },
  created() {
    const storageColumn = this.getSaveTableData()
    this.dropCol = getColumns()
    const uu_Id = this.$store.state.user.userInfo?.id
    this.oldCol =
      storageColumn &&
        storageColumn[`${uu_Id} _commonTableKey_agentTeamBill`]
        ? storageColumn[`${uu_Id} _commonTableKey_agentTeamBill`]
        : this.dropCol
    this.newCol = this.oldCol
  },
  mounted() {
  },
  methods: {
    handleChangeType(val) {
      if (val == 0) {
        this.checkAll = false
        this.checkedCities = [3]
      }
    },
    changeBillEndDate() {
      this.queryData.periodType = 6 // 置空
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities.map(item => item.value) : []
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length
    },
    handleShortcutBtnClick(val) {
      this.searchTime = val
      this.loadData()
    },
    // 查看详情
    goDetail(row) {
      this.rowData = row
      this.showDetail = true
    },
    // 占成详情返回
    detailGoBackFn() {
      this.showDetail = false
      this.rowData = {}
    },
    // 鼠标摁下触发
    handleMounseDown(e, column, $index) {
      this.dragState.dragging = true
      this.dragState.start = parseInt($index - 0)
      // 添加鼠标抬起事件  消除鼠标摁下立刻松开问题
      document.addEventListener('mouseup', this.handleMouseUp)
      // 添加拖拽结束事件
      document.addEventListener('dragend', this.handleMouseUp)
      // 对选中的表头允许其拖拽
      const dragclass = '.el-table__header-wrapper .' + column.id
      const dragDom = document.querySelectorAll(dragclass)
      dragDom.forEach((dom) => {
        // 允许表头块可以被拖拽 draggable 属性 不允许拖拽dragover等相关拖拽事件无法触发
        dom.setAttribute('draggable', true)
      })
    },
    /** 鼠标在拖拽移动时触发 */
    handleDragover(e, column, $index) {
      if (this.dragState.dragging) {
        // 获取当前滚动条的位置
        const scrollDom = this.$refs.elTable.bodyWrapper
        this.scrollX = scrollDom.scrollLeft
        const index = parseInt($index - 0) // 记录起始列
        /** 实时更改鼠标处于表头的位置 */
        if (index - this.dragState.start !== 0) {
          this.dragState.direction =
            index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
          this.dragState.end = parseInt($index - 0)
        } else {
          this.dragState.end = this.dragState.start
          this.dragState.direction = null
        }
      }
    },
    /** 鼠标抬起或拖拽结束触发 */
    handleMouseUp() {
      // 更新拖拽后的表头
      this.headDraged(this.dragState)
      const { end } = this.dragState
      // 初始化拖动状态
      this.dragState = {
        start: end, // 记录最后拖动的位置
        end: -9,
        dragging: false,
        direction: undefined
      }
      document.removeEventListener('mouseup', this.handleMouseUp)
      document.removeEventListener('dragend', this.handleMouseUp)
      setTimeout(() => {
        // 重置拖拽状态
        this.dragState.start = -9
      }, 500)
    },
    // 更新拖拽后的表头
    headDraged({ start, end, direction }) {
      if (direction) {
        const originColumn = this.newCol[start]
        // 有位置交换时，原先位置的元素删除，再在目标处插入
        this.oldCol.splice(start, 1)
        this.oldCol.splice(end, 0, originColumn)
        this.headKey = new Date().getTime() + '' // 更新table key值
        const uu_Id = this.$store.state.user.userInfo.id
        const uidKey = uu_Id + '_commonTableKey_agentTeamBill'
        const getLocalTableData = Storage.get('commonTableKey')
        if (getLocalTableData) {
          Storage.set(
            'commonTableKey',
            Object.assign(getLocalTableData, {
              [uidKey]: this.oldCol
            })
          )
        } else {
          Storage.set('commonTableKey', {
            [uidKey]: this.oldCol
          })
        }
        this.$nextTick(() => {
          // 因为表头重绘后滚动条会移到最左端初始位置，因此如果是在中间部分拖拽，还需要把滚动条在定位到该位置
          this.$refs.elTable.bodyWrapper.scrollLeft = this.scrollX
        })
      }
    },
    // 拖动虚线样式设置
    cellClassName({ columnIndex }) {
      const { start, end, direction } = this.dragState
      const target = columnIndex - 0
      if (target === start) {
        // 被移动的元素
        return 'drag_start'
      } else if (target === end) {
        // 要移动的位置
        return `drag_end_${direction}`
      }
      return ''
    },
    changeTableSort({ column, prop, order }) {
      this.queryData.orderKey = prop
      if (order === 'ascending') {
        // 升序
        this.queryData.orderType = 'asc'
      } else if (column.order === 'descending') {
        // 降序
        this.queryData.orderType = 'desc'
      } else {
        delete this.queryData.orderKey
        delete this.queryData.orderType
      }
      this.loadData()
    },
    loadData() {
      if (this.queryData.proxyType == 1 && !this.queryData.proxyName) {
        this.$message.warning('请输入代理账号')
        return false
      }
      if (this.queryData.proxyType == 0) {
        delete this.queryData.labType
        delete this.queryData.proxyName
      } else {
        this.queryData.labType = this.checkedCities
      }
      const params = {
        ...this.queryData,
        ...this.getParams()
      }
      delete params.periodType
      delete params.billEndDate
      const [startTime, endTime] = this.searchTime || []
      params.cycleStartDate = startTime
        ? dayjs(startTime)
          .startOf('month').format('YYYYMMDD')
        : undefined
      params.cycleEndDate = endTime
        ? dayjs(endTime).endOf('month')
          .format('YYYYMMDD')
        : undefined

      this.childrenAjaxData = JSON.parse(JSON.stringify(params))
      this.loading = true
      this.$api
        .proxyTeamRateBillList(params)
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.tableData = []
            this.tableData = res?.data?.record || []
            this.total = res?.data?.totalRecord || 0
            // this.subSummary = res?.data?.summary || {}
          }
        })
        .catch(() => {
          this.loading = false
        })
      this.$api
        .proxyTeamRateBillTotal(params)
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.totalSummary = res?.data || {
              teamSummary: '',
              teamZhanchengSummary: '',
              platSummary: ''
            }
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    search() {
      this.pageNum = 1
      this.loadData()
    },
    reset() {
      this.pageNum = 1
      this.queryData = {
        proxyType: 0,
        labType: [],
        periodType: 5
      }
      this.checkAll = false
      this.checkedCities = [3]
      this.searchTime = setSearchTime()
      this.loadData()
    },
    handleExportExcel() {
      if (this.queryData.proxyType == 1 && !this.queryData.proxyName) {
        this.$message.warning('请输入代理账号')
        return false
      }

      if (this.queryData.proxyType == 0) {
        delete this.queryData.labType
        delete this.queryData.proxyName
      } else {
        this.queryData.labType = this.checkedCities
      }
      const params = {
        ...this.queryData
      }
      delete params.periodType
      delete params.billEndDate
      const [startTime, endTime] = this.searchTime || []
      params.cycleStartDate = startTime
        ? dayjs(startTime)
          .startOf('month').format('YYYYMMDD')
        : undefined
      params.cycleEndDate = endTime
        ? dayjs(endTime).endOf('month')
          .format('YYYYMMDD')
        : undefined
      this.exportBtnLoading = true
      this.exportExcelPublic({
        api: 'proxyTeamRateBillExport',
        params
      }).finally(() => {
        this.exportBtnLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
.input-with-select {
	width: 110px;
}
.ptop {
	padding-top: 2px;
	margin-left: 10px;
}
::v-deep .el-icon-question:after {
	font-size: 16px;
	margin-left: 0;
}
.totalContent {
	display: flex;
	justify-content: space-around;
	margin: 10px 0px 20px 0px;
	padding: 20px 10px;
	border: 1px solid #ebeef5;
	.totalItem {
		padding: 0 10px;
		margin: 0 10px;
		div {
			text-align: center;
		}
		.num {
			font-size: 30px;
			font-weight: 500;
		}
	}
}
</style>
